package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-12
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {
    @Autowired
    private MinIOService minIOService;

    @Override
    public ResponseResult upload(MultipartFile file) {
        User user = MediaThreadLocalUtil.get();
        //没有登录就返回
        if(user==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //调用minio上传
        String picUrl = minIOService.upload(file);
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection(false);
        wmMaterial.setType(0);
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setUrl(picUrl);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult listByCollection(WmMaterialDto dto) {
//        assert (MediaThreadLocalUtil.get().getUserId()!=null);
        // 获取当前用户的id
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建查询条件
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();

        query.eq(dto.getIsCollection()!=null,WmMaterial::getIsCollection,dto.getIsCollection())
                .eq(WmMaterial::getUserId,user.getUserId())
                .orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        page=page(page,query);
        PageResponseResult<List<WmMaterial>> result = new PageResponseResult<>(dto.getPage(), Integer.parseInt(dto.getSize().toString()), page.getTotal(), page.getRecords());
        return result;

    }
}
